package Yangtz.Cs.Service;

import Yangtz.Cs.DAO.ReaderDao;
import Yangtz.Cs.Entity.BookBean;
import Yangtz.Cs.Entity.ReaderBean;
import Yangtz.Cs.Utils.DataTransmissionUtil;
import Yangtz.Cs.Utils.JDBCUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ReaderService {
    ReaderDao readerDao = new ReaderDao();

    public boolean insert(ReaderBean reader) {
        return readerDao.insert(reader);
    }

    public ArrayList<ReaderBean> findAll() {
        return readerDao.findAll();
    }

    public ReaderBean find(String id) {
        return readerDao.find(id);
    }

    public boolean delete(String id) {
        return readerDao.delete(id);
    }

    public boolean update(ReaderBean reader) {
        return readerDao.update(reader);
    }

    //用于管理员登陆识别
    public ReaderBean isManager(String rdID,String rdPwd) {
        ReaderBean readerBean = readerDao.find(rdID);

        //判断有无该管理员
        if (readerBean != null) {
            //密码是否一致
            if (readerBean.getRdPWd().equals(rdPwd))
                return readerBean;
            else {
                return null;
            }
        } else {
            return null;
        }
    }

    //用于读者登陆识别
    public void LoginIdentify(ReaderBean reader, HttpServletResponse response) throws IOException {

        JSONArray jsonArray = new JSONArray();

        //先通过指定的rdID找reader
        ReaderBean rd = new ReaderDao().find(reader.getRdID());

        //若没找到该reader，返回failed
        if (rd == null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("bkName", "failed");
            jsonArray.add(jsonObject);
            DataTransmissionUtil.sendJsonArrayToAndroid(jsonArray,response);
        } else {                                               //找到该reader，判断密码是否正确
            if (rd.getRdPWd().equals(reader.getRdPWd())) {
                //创建Book实体类list
                List<BookBean> bookList = new ArrayList<>();
                //创建BookService对象来调用findall方法
                BookService bookService = new BookService();
                //拿到所有的书籍对象
                bookList = bookService.findAll();

                //将其封装为数组格式,然后重新赋值给jsonarray，不然jsonarray就是空的
                jsonArray = JSONArray.fromObject(bookList);
                DataTransmissionUtil.sendJsonArrayToAndroid(jsonArray,response);

            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("bkName", "failed");
                jsonArray.add(jsonObject);
                DataTransmissionUtil.sendJsonArrayToAndroid(jsonArray,response);
            }
        }

    }

    public void forgetIdentify(ReaderBean reader,HttpServletResponse response) throws IOException {

        JSONObject jsonObject=new JSONObject();

        String rdID=reader.getRdID();
        if(new ReaderDao().find(rdID)!=null){
            jsonObject.put("fg_tag","success");
            DataTransmissionUtil.sendJsonToAndroid(jsonObject,response);
        }else{
            jsonObject.put("fg_tag","failed");
            DataTransmissionUtil.sendJsonToAndroid(jsonObject,response);
        }

    }


    public void ResetPwd(ReaderBean reader,HttpServletResponse response) {

        JSONObject jsonObject=new JSONObject();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 获得数据的连接
            conn = new JDBCUtil().GetConnection();
            // 获得Statement对象
            stmt = conn.createStatement();
            // 发送SQL语句

            String sql = "UPDATE TB_Reader set " +
                    "rdPwd='" + reader.getRdPWd() +
                    "' WHERE rdID=" + reader.getRdID();

            int num = stmt.executeUpdate(sql);
            if (num > 0) {
                jsonObject.put("reset_tag","success");
                DataTransmissionUtil.sendJsonToAndroid(jsonObject,response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.release(rs, stmt, conn);
        }
    }

    public boolean ChangeINfo(JSONObject jsonObject) {


        Connection conn = null;
        Statement stmt = null;
        try {
            // 获得数据的连接
            conn = new JDBCUtil().GetConnection();
            // 获得Statement对象
            stmt = conn.createStatement();
            // 发送SQL语句

            String sql = "UPDATE TB_Reader set ";

            String keyName = null;
            String value = null;
            

            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                keyName = keys.next();
                value = jsonObject.optString(keyName);
                if (!(keyName.trim().equals("rdPwd1") || keyName.trim().equals("rdID"))) {
                    sql += keyName + "= '" + value + "',";
                }
            }
            //去掉最后一位的逗号
            sql = sql.substring(0, sql.length() - 1);
            sql += " where " + keyName + " = '" + value + "'";

            int num = stmt.executeUpdate(sql);
            if (num > 0) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

}
